
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/char_x.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/current_voltage_chart.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/temperature_chart.dart';
import 'package:yt_devops/pages/site/site_statis_data/show_full_screen_btn.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import '../../../../../site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';

/**
 *
 * @Description TODO
 * @Author liuer
 * @CreateTime 2024年03月07日 09:22
 */
class EvChargeChart extends StatefulWidget {
  final int? deviceId;

  const EvChargeChart(this.deviceId, {super.key});

  @override
  State<EvChargeChart> createState() => _EvChargeChartState();
}

class _EvChargeChartState extends State<EvChargeChart> {
  List<dynamic> gunTemperatureData = []; //枪温度
  List<dynamic> maxTemperatureData = []; //单体电池最高温度
  List<dynamic> minTemperatureData = []; //单体电池最低温度
  List<dynamic> gunPositiveTemperatureData = []; //充电枪正极温度
  List<dynamic> gunNegativeTemperatureData = []; //充电枪负极温度

  List<dynamic> originGunTemperatureData = []; //枪温度
  List<dynamic> originMaxTemperatureData = []; //单体电池最高温度
  List<dynamic> originMinTemperatureData = []; //单体电池最低温度
  List<dynamic> originGunPositiveTemperatureData = []; //充电枪正极温度
  List<dynamic> originGunNegativeTemperatureData = []; //充电枪负极温度

  List<dynamic> maxVoltage = [];//最高允许充电电压
  List<dynamic> needVoltage = [];//需求电压
  List<dynamic> outVoltage = [];//充电输出电压
  List<dynamic> bmsVoltage = [];//BMS测量电压
  List<dynamic> needCurrent = [];//需求电流
  List<dynamic> maxCurrent = [];//最高允许充电电流
  List<dynamic> outCurrent = [];//充电输出电流
  List<dynamic> bmsCurrent = [];//BMS测量电流

  List<dynamic> originMaxVoltage = [];//最高允许充电电压
  List<dynamic> originNeedVoltage = [];//需求电压
  List<dynamic> originOutVoltage = [];//充电输出电压
  List<dynamic> originBmsVoltage = [];//BMS测量电压
  List<dynamic> originNeedCurrent = [];//需求电流
  List<dynamic> originMaxCurrent = [];//最高允许充电电流
  List<dynamic> originOutCurrent = [];//充电输出电流
  List<dynamic> originBmsCurrent = [];//BMS测量电流
  List list = ChartXDate.getData();
  DeviceServices deviceServices = DeviceServices();
  int divisor = 30;//页面展示的数据条数
  int remainder = 1;//页面取余的数值 通过计算获得

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initData();//初始化数据
    if (widget.deviceId != null) {
      _getVoltageAndCurrent();
      _getTemperature();
    }
  }

  ///初始化数据
  initData(){
    for (int i = 0; i < list.length; i++) {
      var element = list[i];
      List tempList = [];
      tempList.add(element.substring(11, 16));
      tempList.add('--');
      originGunTemperatureData.add(tempList);
    }
    originMaxTemperatureData = List.from(originGunTemperatureData);
    originMinTemperatureData = List.from(originGunTemperatureData);
    originGunPositiveTemperatureData = List.from(originGunTemperatureData);
    originGunNegativeTemperatureData = List.from(originGunTemperatureData);
    originMaxVoltage = List.from(originGunTemperatureData);//最高允许充电电压
    originNeedVoltage = List.from(originGunTemperatureData);//需求电压
    originOutVoltage = List.from(originGunTemperatureData);//充电输出电压
    originBmsVoltage = List.from(originGunTemperatureData);//BMS测量电压
    originNeedCurrent = List.from(originGunTemperatureData);//需求电流
    originMaxCurrent = List.from(originGunTemperatureData);//最高允许充电电流
    originOutCurrent = List.from(originGunTemperatureData);//充电输出电流
    originBmsCurrent = List.from(originGunTemperatureData);//BMS测量电流
  }
  ///获取电流电压曲线
  _getVoltageAndCurrent() async {
    var param = {
      'deviceId': widget.deviceId,
    };
    var result = await  deviceServices.getGunVoltageAndCurrent(param, onError: (error) {
      dismissLoading();
      showError(error.message);
      return false;
    });
    Log.d('result===' + result.toString());
    if(result != null){
      List tempList = result;
      for (var element in tempList) {
        if(element['key'] != null && element['key'] == 'gcmaxoutvo'){
          maxVoltage = _handleData(originMaxVoltage,element['values']);
        }
        if(element['key'] != null && element['key'] == 'gxqu'){
          needVoltage = _handleData(originNeedVoltage,element['values']);
        }
        if(element['key'] != null && element['key'] == 'gcu'){
          outVoltage = _handleData(originOutVoltage,element['values']);
        }
        if(element['key'] != null && element['key'] == 'gcut'){
          bmsVoltage = _handleData(originBmsVoltage,element['values']);
        }
        if(element['key'] != null && element['key'] == 'gcmaxoutcu'){
          maxCurrent = _handleData(originMaxCurrent,element['values']);
        }if(element['key'] != null && element['key'] == 'gxqi'){
          needCurrent = _handleData(originNeedCurrent,element['values']);
        }
        if(element['key'] != null && element['key'] == 'gci'){
          outCurrent = _handleData(originOutCurrent, element['values']);
        }
        if(element['key'] != null && element['key'] == 'gxqi'){
          bmsCurrent = _handleData(originBmsCurrent,element['values']);
        }
      }
      setState(() {
        // Log.d('bmsCurrent===' + bmsCurrent.toString());
        // Log.d('needVoltage===' + needVoltage.toString());
        // Log.d('outVoltage===' + outVoltage.toString());
        // Log.d('bmsVoltage===' + bmsVoltage.toString());
        // Log.d('maxCurrent===' + maxCurrent.toString());
        // Log.d('needCurrent===' + needCurrent.toString());

      });
    }
  }

  List<dynamic> _handleData(List originList,
      List? dataList
      ){
    List <dynamic> returnList = [];

    if(dataList !=null && dataList.isNotEmpty){
      Map map = {};
      for (var element in dataList) {
        String key = element['eventTs'].substring(11, 16);
        var value = element['val'];
        if(value != null){
          map[key] = value.toString();
        }
      }
      for (var element in originList) {
        List <dynamic> elementList = List.from(element);
        if(map[elementList[0].toString()] != null){
          elementList[1] = map[elementList[0].toString()].toString();
        }
        returnList.add(elementList);
      }
    }else{
      returnList = List.from(originList);
    }
    return returnList;
  }

  List<dynamic> _showData(List originList,){
    return originList;
    List <dynamic> returnList = [];
    for (int i = 0; i < originList.length; i++) {
      var element = originList[i];
      if (i % remainder == 0) {
        returnList.add(element);
      }
    }
    return returnList;
  }

  ///获取温度曲线
  _getTemperature() async {
    var param = {
      'deviceId': widget.deviceId,
    };
    var result = await deviceServices.getGunTemperature(param, onError: (error) {
      dismissLoading();
      showError(error.message);
      return false;
    });
    if(result != null){
      List tempList = result;
      for (var element in tempList) {
        if(element['key'] != null && element['key'] == 'gdct'){
          gunPositiveTemperatureData = gunTemperatureData = _handleData(originGunTemperatureData,element['values']);
        }
        if(element['key'] != null && element['key'] == 'ght'){
          maxTemperatureData = _handleData(originMaxTemperatureData,element['values']);
        }
        if(element['key'] != null && element['key'] == 'glt'){
          minTemperatureData = _handleData(originMinTemperatureData,element['values']);
        }

        if(element['key'] != null && element['key'] == 'gdct2'){
          gunNegativeTemperatureData = _handleData(originGunNegativeTemperatureData,element['values']);
        }
      }
      setState(() {

      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      // color: Colors.white,
      child: ListView(
        children: [
          Container(
              height: 53,
              padding:
                  EdgeInsets.only(left: 16.w, right: 16.w, top: 20, bottom: 10),
              color: Colors.white,
              alignment: Alignment.centerLeft,
              child: Text(
                ResKey.voltageCurrentCurve.tr,
                style: ytTextStyle(fontSize: 18, fontWeight: FontWeight.w500),
              )),
          Container(
              height: 40,
              color: Colors.white,
              child: Row(
                children: [
                  Spacer(),

                  ShowFullScreenBtn(onTap: (){
                    Get.toNamed(RouterPath.voltageCurrentFullChart,
                        arguments: {
                        "maxVoltage": maxVoltage,
                        "needVoltage":needVoltage,
                        "outVoltage": outVoltage ,
                        "bmsVoltage":bmsVoltage ,
                        "needCurrent": needCurrent,
                        "maxCurrent": maxCurrent,
                        "outCurrent": outCurrent,
                        "bmsCurrent": bmsCurrent,}
                    );
                  },
                  )
                ],
              )),
          Container(
              height: 320 + 40,
              color: Colors.white,
              child: KeepAliveWrapper(CurrentVoltageChart(
                  maxVoltage: _showData(maxVoltage),
                  needVoltage: _showData(needVoltage),
                  outVoltage: _showData(outVoltage),
                  bmsVoltage: _showData(bmsVoltage),
                  needCurrent: _showData(needCurrent),
                  maxCurrent: _showData(maxCurrent),
                  outCurrent: _showData(outCurrent),
                  bmsCurrent: _showData(bmsCurrent)))),
          Container(
              height: 53,
              margin: const EdgeInsets.only(top: 10),
              padding:
                  EdgeInsets.only(left: 16.w, right: 16.w, top: 20, bottom: 10),
              color: Colors.white,
              alignment: Alignment.centerLeft,
              child: Text(
                ResKey.temperatureCurve.tr,
                style: ytTextStyle(fontSize: 18, fontWeight: FontWeight.w500),
              )),
          Container(
              height: 40,
              color: Colors.white,
              child: Row(
                children: [
                  Spacer(),
                  ShowFullScreenBtn(onTap: (){
                    Log.d('originMaxCurrent==' + originMaxCurrent.toString());
                    Get.toNamed(RouterPath.temperatureFullChart,
                      arguments: {
                        "gunTemperatureData": gunTemperatureData,
                        "maxTemperatureData": maxTemperatureData,
                        "minTemperatureData": minTemperatureData,
                        "gunPositiveTemperatureData": gunPositiveTemperatureData,
                        "gunNegativeTemperatureData": gunNegativeTemperatureData,}
                    );
                  },
)
                ],
              )),
          Container(
              height: 290,
              color: Colors.white,
              child: TemperatureChart(
                  gunTemperatureData: _showData(gunTemperatureData),
                  maxTemperatureData: _showData(maxTemperatureData),
                  minTemperatureData: _showData(minTemperatureData),
                  gunPositiveTemperatureData: _showData(gunPositiveTemperatureData),
                  gunNegativeTemperatureData: _showData(gunNegativeTemperatureData))),

          // Container(
          //   height: 400,
          // )
        ],
      ),
    );
  }
}
